<template>
  <div>
    <h1>品牌管理</h1>
    <table>
      <thead>
        <tr>
          <th>编号</th>
          <th>资产名称</th>
          <th>价格</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- 这里的template只是起一个包裹作用,不会被渲染成真实的页面标签 -->
        <template v-if="brandList.length>0">
          <tr v-for="(item, index) in brandList" :key="item.id">
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td :class="{ active: item.price >= 199 }">{{ item.price }}</td>
            <td>{{ item.createTime | formatTime("🌗") | add··Author }}</td>
            <td>
              <a href="javascript:;" @click="del(index)">删除</a>
            </td>
          </tr>
        </template>

        <tr v-else>
          <td colspan="5">当前数据为空！</td>
        </tr>
      </tbody>
    </table>

    <input type="text" v-model="name" />
    <input type="number" v-model.number="price" />

    <button class="btn" @click="add" :time="time | formatTime('⭐')">添加资产</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      brandList: [
        { id: 101, name: "外套", price: 80, createTime: new Date() },
        { id: 106, name: "外套2", price: 1993, createTime: new Date() },
      ],
      name: "",
      price: 0,
      time: new Date()
    };
  },
  methods: {
    add() {
      // 找到id最大值加1
      let id;
      if (this.brandList.length === 0) {
        id = 1;
      } else {
        // this.brandList.sort((a, b) => a.id - b.id)
        // id = this.brandList[this.brandList.length - 1].id + 1

        let idArr = this.brandList.map(item => item.id)
        // id = Math.max(...idArr) + 1
        // apply传参时使用数组
        id  = Math.max.apply(null, idArr) + 1
      }

      let temp = {
        id: id,
        name: this.name,
        price: this.price,
        createTime: new Date(),
      };
      this.brandList.push(temp)
    },
    del(index) {
      this.brandList.splice(index, 1)
    }
  },
  filters: {
    formatTime(time, icon) {
      let y = time.getFullYear()
      let m = time.getMonth() + 1
      return `${icon} ${y}-${m}`
    },
    addAuthor(str) {
      return str + 'Master Yih'
    }
  }
};
</script>

<style>
table {
  margin: 15px 0;
  width: 600px;
  border-collapse: collapse;
}
td {
  border: 1px solid #000;
}
.btn {
  border: none;
  border-radius: 4px;
  width: 140px;
  height: 30px;
  color: white;
  text-align: center;
  line-height: 30px;
  background-color: #007bff;
}
.active {
  color: red;
}
</style>